import { defineComponent, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ShopInfo from '@/components/ShopInfo'
import Cart from './Cart'
import ShopContent from './ShopContent'
import { Shop } from '@/types/model'
import { getShopApi } from '@/api/shop'
import { useSearchEffect } from '@/hooks/useSearch'
import SearchInput from '@/components/SearchInput'

/* 获取当前商铺信息 */
const useShopInfoEffect = () => {
  const route = useRoute()
  const data = reactive({
    shop: {}
  })
  const getShopData = async () => {
    const result = await getShopApi(route.params.id as string)
    if (result.code === 0) {
      data.shop = result.data
    }
  }

  return {
    data,
    getShopData
  }
}

/* 返回首页 */
const useBackRouterEffect = () => {
  const router = useRouter()
  const handleBackClick = () => {
    router.back()
  }
  return handleBackClick
}

export default defineComponent({
  name: 'Shop',
  setup () {
    const { data, getShopData } = useShopInfoEffect()
    const handleBackClick = useBackRouterEffect()
    const { search, searchText } = useSearchEffect()
    getShopData()

    /* render 函数 */
    return () => {
      return (
        <div class="shop">
          <div class="shop__search">
            <div class="shop__search__back" onClick={ handleBackClick }>
              <i class="iconfont icon-back"></i>
            </div>
            <SearchInput
              v-model={ searchText.value }
              onKeyup={ search }
              placeholder="请输入商家名称搜索"
            />
          </div>
          <ShopInfo shop={ data.shop as Shop } hideBorder />
          <ShopContent shopName={ (data.shop as Shop).title || '' } />
          <Cart shopName={ (data.shop as Shop).title || '' } />
        </div>
      )
    }
  }
})
